package com.jiezhuo.filter;

import com.jiezhuo.cache.RedisCache;
import com.jiezhuo.entity.LoginUser;
import com.jiezhuo.utils.JwtUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class  JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Autowired
    private RedisCache redisCache;

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest resuest, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = resuest.getRequestURI();
        //获取token
        String token = resuest.getHeader("token");
        if (!StringUtils.hasLength(token) ||resuest.getRequestURI().equals("/authen/jzg")||resuest.getRequestURI().equals("/authen/jss")||resuest.getRequestURI().equals("/authen/xxgl")||resuest.getRequestURI().equals("/authen/jw")) {
            //放行
            filterChain.doFilter(resuest, response);
            return;
        }
        if(resuest.getRequestURI().equals("/user/login")){
            filterChain.doFilter(resuest, response);
            return;
        }
        //解析token
//        String userId;
//        try {
//            Claims claims = JwtUtil.parseJWT(token);
//            userId = claims.get("id").toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("token非法");
//        }
//        JwtUtil.copyJwtToken(token);
        //从redis中获取用户信息
        String redisKey = "login:" + token;

        Object cacheObject = redisCache.getCacheObject(redisKey);
        LoginUser loginUser = redisCache.getCacheObject(redisKey);

        if (Objects.isNull(loginUser)) {

            throw new RuntimeException("用户未登录");
        }
        redisCache.setCacheObject("login:"+token,loginUser,120, TimeUnit.MINUTES);
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(resuest, response);
        return;
    }
}
